/*
 *所有关于cw_djlc_configuration_new_energy类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*cw_djlc_configuration_new_energyService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Finance.IRepositories;
using System.Collections.Generic;
using VOL.Core.DBManager;
using System;
using System.Collections;
using Confluent.Kafka;

namespace VOL.Finance.Services
{
    public partial class cw_djlc_configuration_new_energyService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Icw_djlc_configuration_new_energyRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public cw_djlc_configuration_new_energyService(
            Icw_djlc_configuration_new_energyRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();

        public override PageGridData<cw_djlc_configuration_new_energy> GetPageData(PageDataOptions options)
        {
            QueryRelativeExpression = (IQueryable<cw_djlc_configuration_new_energy> queryable) =>
            {
                queryable = queryable.Where(x => x.del_flag == "0");
                return queryable;
            };
            return base.GetPageData(options);
        }

        public override WebResponseContent Del(object[] keys, bool delList = true)
        {
            //配置表在删除操作时，如果发现该配置表全删除没有数据了，需要同步更新定价流程主表is_have_disposition = 0
            var djlcId = "1";
            DelOnExecuting = (object[] _keys) =>
            {
                if (_keys!=null)
                {
                    cw_djlc_configuration_new_energy energy = DBServerProvider.DbContext.Set<cw_djlc_configuration_new_energy>().Where(c => c.cw_djlc_configuration_new_energy_id == Guid.Parse(_keys[0].ToString())).ToList().FirstOrDefault();
                    djlcId = energy != null ? energy.cw_djlc_djzb_id.ToString() : "";
                }
                return webResponse.OK();
            };
            DelOnExecuted = (object[] _keys) =>
            {
                List<cw_djlc_configuration_new_energy> list = DBServerProvider.DbContext.Set<cw_djlc_configuration_new_energy>().Where(c => c.cw_djlc_djzb_id == Guid.Parse(djlcId)).ToList();
                if (list == null || list.Count == 0)
                {
                    cw_djlc_djzb djzb = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(c => c.cw_djlc_djzb_id == Guid.Parse(djlcId)).ToList().FirstOrDefault();
                    if (djzb!=null)
                    {
                        djzb.is_have_disposition = 0;
                        DBServerProvider.DbContext.Update(djzb);
                        DBServerProvider.DbContext.SaveChanges();
                    }  
                }
                return webResponse.OK();
            };
            return base.Del(keys, delList);
        }
        public virtual WebResponseContent Import_Configuration(List<IFormFile> files, string id)
        {
            ImportOnExecuting = (List<cw_djlc_configuration_new_energy> list) =>
            {
                if (list.Count < 2)
                {
                    return webResponse.Error("配置表最少上传两条，请重新上传！");
                }
                var dapper = DBServerProvider.SqlDapper;
                try
                {
                    //逻辑删除之前上传的数据
                    //string sql = "update cw_djlc_configuration_new_energy set del_flag = 1 where cw_djlc_djzb_id = @value ";
                    //var data = dapper.ExcuteNonQuery(sql, new { value = id });

                    //定价流程主表 配置项类型更新 1传统车 2新能源车
                    string sql2 = "update cw_djlc_djzb set configuration_type = 2 , is_have_disposition = 1 where cw_djlc_djzb_id = @value ";
                    var data2 = dapper.ExcuteNonQuery(sql2, new { value = id });
                    cw_djlc_djzb djzb = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(c => c.cw_djlc_djzb_id == Guid.Parse(id)).ToList().LastOrDefault();
                    string newmaterialnum = djzb.newmaterialnum;//需求物料号
                    foreach (cw_djlc_configuration_new_energy item in list)
                    {
                        if (!string.IsNullOrEmpty(newmaterialnum) && !string.IsNullOrEmpty(item.new_materialnum) && newmaterialnum.Equals(item.new_materialnum))
                        {
                            djzb.vehicletype = item.vehicle_model;//车型
                            djzb.drivetype = item.driving_form;//驱动形式
                            djzb.fuel = item.fuel_type;//燃料
                            djzb.pilothouse = item.cage;//驾驶室
                            djzb.enginetype = item.xny_power_battery_total_electricity; //动力电池总电量（kWh）新能源车的
                            djzb.transmissiontype = item.transmission_model;//变速器型号
                            djzb.sale_keyword = djzb.salechannel + item.cage + item.fuel_type + item.vehicle_model + item.driving_form; //销售关键词
                            djzb.serialnum = item.serial_number;
                            //根据配置表的相关信息去财务主表去匹配财务变动取值信息，如果匹配到就将该财务主表uuid更新到定价流程主表；
                            cw_djlc_cwzb cwzb = DBServerProvider.DbContext.Set<cw_djlc_cwzb>().Where(c => c.salechannel.Contains(djzb.salechannel) && item.cage.Contains(c.pilothouse) && c.fuel.Contains(item.fuel_type) && c.vehicletype.Contains(item.vehicle_model) && c.drivetype.Contains(item.driving_form)).ToList().LastOrDefault();
                            if (cwzb != null)
                            {
                                djzb.cw_djlc_cwzb_id = cwzb.cw_djlc_cwzb_id;
                            }
                            DBServerProvider.DbContext.Update(djzb);
                            DBServerProvider.DbContext.SaveChanges();
                        }
                    }
                    dapper.Commit();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    dapper.Rollback();
                }
                return webResponse.OK();
            };
            return base.ImportConfigurationTradition(files, id);
        }
    }
}
